<?php
/**
 * 入驻管理
*
* @author karl <karl.tang@aiyuangong.com>
* @link http://www.aiyuangong.com
*/
namespace app\admin\controller\store;

use app\admin\Controller;
use think\Exception;
use think\Db;

class StoreJoinin extends Controller
{
    use\app\admin\traits\controller\Controller;

    protected static $blacklist = [
        'deleteforever',
        'clear'
    ];

    protected function beforeIndex()
    {
        // 状态列表
        $stateList = [
            STORE_JOIN_STATE_NEW => '新申请',
            STORE_JOIN_STATE_PAY => '已付款',
            STORE_JOIN_STATE_VERIFY_SUCCESS => '待付款',
            STORE_JOIN_STATE_VERIFY_FAIL => '审核失败',
            STORE_JOIN_STATE_PAY_FAIL => '付款审核失败',
            STORE_JOIN_STATE_FINAL => '开店成功'
        ];
        // 审核状态
        $auditState = [
            STORE_JOIN_STATE_NEW,
            STORE_JOIN_STATE_PAY
        ];
        // 失败状态
        $failState = [
            STORE_JOIN_STATE_VERIFY_FAIL,
            STORE_JOIN_STATE_PAY_FAIL
        ];
        // 成功状态
        $successState = [
            STORE_JOIN_STATE_FINAL
        ];
        $this->view->assign('state_list', $stateList);
        $this->view->assign('audit_state', $auditState);
        $this->view->assign('success_state', $successState);
    }

    /**
     * 开店审核
     */
    public function audit()
    {
        $member_id = $this->request->param('member_id/d');
        $message = $this->request->param('message/d'); // 审核备注
        if ($this->request->isPost()) {
            $joinin_detail = Db::name('store_joinin')->where([
                'member_id' => $member_id
            ])->find();
            switch (intval($joinin_detail['joinin_state'])) {
                case STORE_JOIN_STATE_NEW:
                    return $this->_joinin_pass($joinin_detail);
                    break;
                case STORE_JOIN_STATE_PAY:
                    return $this->_joinin_open($joinin_detail);
                    break;
                default:
                    return ajax_return_adv_error('参数错误');
                    break;
            }
        } else {
            // 审核页
            $member_id = $this->request->param('member_id/d');
            if (! $member_id) {
                throw new Exception("缺少参数ID");
            }
            $joinin = Db::name('store_joinin')->where([
                'member_id' => $member_id
            ])->find();
            if (! $joinin) {
                throw new Exception(404, '该记录不存在');
            }
            
            // 处理经营类目与佣金比例成数组
            if (! empty($joinin['store_class_names']) && ! empty($joinin['store_class_commis_rates'])) {
                $joinin['store_class_names'] = unserialize($joinin['store_class_names']);
                $class_name = [];
                foreach ($joinin['store_class_names'] as $key => $val) {
                    $tmp = explode(',', $val);
                    $class_name[] = [
                        'class_1_name' => $tmp[0],
                        'class_2_name' => $tmp[1]
                    ];
                }
                $joinin['store_class_names'] = $class_name;
                $joinin['store_class_commis_rates'] = explode(',', $joinin['store_class_commis_rates']);
            }
            // 审核状态
            $auditState = [
                STORE_JOIN_STATE_NEW,
                STORE_JOIN_STATE_PAY
            ];
            // 失败和成功状态（显示审核意见用）
            $completeState = [
                STORE_JOIN_STATE_VERIFY_FAIL,
                STORE_JOIN_STATE_PAY_FAIL,
                STORE_JOIN_STATE_FINAL
            ];
            $this->view->assign('audit_state', $auditState);
            $this->view->assign('complete_state', $completeState);
            $this->view->assign("joinin_info", $joinin);
            
            return $this->view->fetch();
        }
    }

    private function _joinin_pass($joinin_detail)
    {
        $param = array();
        $param['joinin_state'] = $this->request->param('verify_type/s') === 'pass' ? STORE_JOIN_STATE_VERIFY_SUCCESS : STORE_JOIN_STATE_VERIFY_FAIL;
        $param['joinin_message'] = $this->request->param('message');
        $param['paying_amount'] = abs(floatval($this->request->param('paying_amount')));
        $param['store_class_commis_rates'] = implode(',', $this->request->param('commis_rate/a'));
        try {
            Db::name('store_joinin')->where([
                'member_id' => $this->request->param('member_id/d')
            ])
                ->update($param);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        if ($param['joinin_state'] == STORE_JOIN_STATE_VERIFY_FAIL) {
            return ajax_return_adv("店铺入驻已拒绝");
        }
        if ($param['paying_amount'] > 0) {
            return ajax_return_adv("店铺入驻申请审核完成");
        } else {
            // 如果开店支付费用为零，则审核通过后直接开通，无需再上传付款凭证
            return $this->_joinin_open($joinin_detail);
        }
    }

    private function _joinin_open($joinin_detail)
    {
        // 验证卖家用户名是否已经存在
        $result = Db::name('store')->where([
            'seller_name' => $joinin_detail['seller_name']
        ])->find();
        if (count($result) > 0) {
            return ajax_return_error("卖家用户名已存在");
        }
        
        $param = [];
        $param['joinin_state'] = $this->request->param('verify_type/s') === 'pass' ? STORE_JOIN_STATE_FINAL : STORE_JOIN_STATE_PAY_FAIL;
        $param['joinin_message'] = $this->request->param('message/s');
        Db::startTrans();
        try {
            $model = Db::name('store_joinin');
            $ret = $model->where([
                'member_id' => $this->request->param('member_id/d')
            ])
                ->update($param);
            
            if ($this->request->param('verify_type/s') === 'pass') {
                // 开店
                $shop_array = array();
                $shop_array['member_id'] = $joinin_detail['member_id'];
                $shop_array['member_name'] = $joinin_detail['member_name'];
                $shop_array['seller_name'] = $joinin_detail['seller_name'];
                $shop_array['grade_id'] = $joinin_detail['sg_id'];
                $shop_array['name'] = $joinin_detail['store_name'];
                $shop_array['sc_id'] = $joinin_detail['sc_id'];
                $shop_array['company_name'] = $joinin_detail['company_name'];
                $shop_array['areacode'] = $joinin_detail['company_area_code'];
                $shop_array['area_info'] = $joinin_detail['company_address'];
                $shop_array['address'] = $joinin_detail['company_address_detail'];
                $shop_array['zip'] = '';
                $shop_array['store_state'] = 1;
                $shop_array['status'] = 1;
                $shop_array['isdelete'] = 0;
                $shop_array['time'] = time();
                $shop_array['end_time'] = strtotime(date('Y-m-d 23:59:59', strtotime('+1 day')) . " +" . intval($joinin_detail['joinin_year']) . " year");
                $store_id = Db::name('store')->insertGetId($shop_array);
                $state = true;
                
                if ($store_id) {
                    // 写入卖家账号
                    $seller_array = array();
                    $seller_array['seller_name'] = $joinin_detail['seller_name'];
                    $seller_array['member_id'] = $joinin_detail['member_id'];
                    $seller_array['seller_group_id'] = 0;
                    $seller_array['store_id'] = $store_id;
                    $seller_array['is_admin'] = 1;
                    $state = Db::name('seller')->insert($seller_array);
                }
                
                if ($state) {
                    // 添加相册默认
                    $album_model = Db::name('album_class');
                    $album_arr = array();
                    $album_arr['aclass_name'] = '默认相册';
                    $album_arr['store_id'] = $store_id;
                    $album_arr['aclass_des'] = '';
                    $album_arr['aclass_sort'] = '255';
                    $album_arr['aclass_cover'] = '';
                    $album_arr['upload_time'] = time();
                    $album_arr['is_default'] = '1';
                    $album_model->insert($album_arr);
                    
                    // 插入店铺扩展表
                    /*
                     * Db::name('store_extend')->insert(array( 'store_id' => $store_id ));
                     */
                    
                    // 插入店铺绑定分类表
                    $store_bind_class_array = array();
                    $store_bind_class = unserialize($joinin_detail['store_class_ids']);
                    $store_bind_commis_rates = explode(',', $joinin_detail['store_class_commis_rates']);
                    for ($i = 0, $length = count($store_bind_class); $i < $length; $i ++) {
                        list ($class1, $class2, $class3) = explode(',', $store_bind_class[$i]);
                        $store_bind_class_array[] = array(
                            'store_id' => $store_id,
                            'commis_rate' => $store_bind_commis_rates[$i],
                            'class_1' => $class1,
                            'class_2' => $class2,
                            // 'class_3' => $class3,
                            'state' => 1
                        );
                    }
                    $model_store_bind_class = Db::name('store_bind_class');
                    $model_store_bind_class->insertAll($store_bind_class_array);
                    Db::commit();
                    return ajax_return_adv("店铺开店成功");
                }
            } else {
                Db::rollback();
                return ajax_return_adv('店铺开店拒绝');
            }
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
    }
}